
# -*- codeing = utf-8 -*-
# @Time: 2022/6/17 1:09
# @Author: Foxhuty
# @File: email_received.py
# @Software: PyCharm
# @Based on python 3.10

from imbox import Imbox
import datetime
import os
import time


def make_directory(f):
    def wrapper(*args, **kwargs):
        if not os.path.exists(f'D:\\爬虫数据\\{file_folder}'):
            os.makedirs(f'D:\\爬虫数据\\{file_folder}')
        result = f(*args, **kwargs)
        return result

    return wrapper


@make_directory
def get_mail_attachments(year, month, day):
    start = time.time()
    n = 0
    with Imbox(mail_host, username=sender, password=mail_pass, ssl=True) as imbox:
        all_inbox_messages = imbox.messages()
        for uid, message in all_inbox_messages:
            try:
                mail_date = message.parsed_date.date()
                date_filter = datetime.date(year, month, day)
                if mail_date >= date_filter:
                    if message.attachments:
                        for attachment in message.attachments:
                            with open(f'D://爬虫数据//{file_folder}//{attachment["filename"]}', mode='wb') as f:
                                f.write(attachment['content'].getvalue())
                                f.close()
                                imbox.mark_seen(uid)
                                n += 1
                                print(f'第{n}封邮件:{mail_date}---{message.subject}----{attachment["filename"]}---下载完成!')
            except:

                pass
        end = time.time()
        time_spent = round((end - start) / 60, 1)
        print(f'----------邮件接收完毕,共计用时{time_spent}分钟---------------')


if __name__ == '__main__':
    # 设定邮件存放文件夹
    file_folder = '2022年应聘邮件222'
    mail_host = 'imap.qq.com'
    # 设定接收邮箱许可证密码
    mail_pass = 'gdhprdriyijibjfi'
    # mail_pass = 'tensjeayhyelccbe'
    # 可修改接收邮箱email:
    # sender = '1801007676@qq.com'
    sender = 'foxhuty@qq.com'
    # 传入接收邮件的日期过滤条件：如要接收2020年1月1日及之后的所有邮件，在函数参数中传入2020，1，1
    get_mail_attachments(2022, 1, 1)
